import axios from 'axios'
import md5 from 'js-md5'
import User from './user'

const clientKey = 'f7hcLXDDkLiJoTiSUzg7rRHSqfuFbzEC'

// 请求响应超时时间
axios.defaults.timeout = 30000
axios.defaults.withCredentials = true 
// 请求拦截器
axios.interceptors.request.use(
  // 在请求头里面设置一些参数
  function (config) {
    // 将s改成了l
    var ccn = localStorage.getItem('ccn')
    if (!ccn) {
      // 使用md5生成ccn放在请求头里面
      ccn = md5(Math.random() * 10000000 + '')
      localStorage.setItem('ccn', ccn)
    }
    config.headers['role'] = '2'
    config.headers['ccn'] = ccn
    var cid = localStorage.getItem('vcid')
    var ua = navigator.userAgent
    cid = md5(ua + ccn + clientKey)
    localStorage.setItem('vcid', cid)
    config.headers['cid'] = cid
    var token = User.getToken()
    if (token) {
      config.headers['token'] = encodeURIComponent(token)
    }

    return config
  },
  function (err) {
    return Promise.reject(err)
  }
)
// 响应拦截器
axios.interceptors.response.use(
  response => {
    return Promise.resolve(response)
  },
  err => {
    return Promise.reject(err)
  }
)

// 接口基础地址
const baseURL = 'https://api.vote.jdytp.com/'
// const baseURL = 'http://127.0.0.1:8100/'

// 封装自己的get/post方法
export default {
  serverUrl: baseURL,

  post: function (path = '', data = {}) {
    return new Promise(function (resolve, reject) {
      axios
        .post(baseURL + path, data)
        .then(function (response) {
          resolve(response.data)
        })
        .catch(function (error) {
          reject(error)
        })
    })
  },
  get: function (url, params = null) {
    return new Promise((resolve, reject) => {
      axios
        .get(baseURL + url, {
          params: params
        })
        .then(res => {
          resolve(res.data)
        })
        .catch(err => {
          reject(err)
        })
    })
  },
  delete: function (url, params = null) {
    return new Promise((resolve, reject) => {
      axios
        .delete(baseURL + url, {
          params: params
        })
        .then(res => {
          resolve(res.data)
        })
        .catch(err => {
          reject(err)
        })
    })
  },
  // 上传文件方法
  upload: function (url, file) {
    var data = new FormData()
    data.append('file', file)

    return new Promise((resolve, reject) => {
      axios
        .post(baseURL + url, data, {
          headers: {
            'Content-Type': 'multipart/form-data'
          }
        })
        .then(res => {
          resolve(res.data)
        })
        .catch(err => {
          reject(err)
        })
    })
  }
}
